package com.ruoyi.common.utils;

import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @ClassName RequestBodyFilter
 * @Description TODO
 * @Author drx
 * @Date 2023/5/31 14:18
 */
public class RequestBodyFilter  implements Filter{
    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest)request;
            String method = httpServletRequest.getMethod();
            String contentType = httpServletRequest.getContentType()==null?"":httpServletRequest.getContentType();
            //如果是POST请求并且不是文件上传
            if((contentType.equals(MediaType.APPLICATION_JSON_UTF8_VALUE) || contentType.equals(MediaType.APPLICATION_JSON_VALUE))&&!contentType.equals(MediaType.MULTIPART_FORM_DATA_VALUE)){
                //重新生成ServletRequest  这个新的ServletRequest 获取流时会将流的数据重写进流里面
                requestWrapper = new RequestReaderHttpServletRequestWrapper((HttpServletRequest) request);
            }

        }
        if (requestWrapper == null) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        System.out.println("init");
    }
}
